<template>
  <view class="download-page">
    <!-- <view class="page-header">
      <view class="header-left" @click="navigateBack">
        <view class="icon icon-back" style="font-size: 24px; color: #333;">‹</view>
      </view>
      <view class="header-title">下载历史</view>
      <view class="header-right"></view>
    </view> -->
    
    <!-- 下载列表 -->
    <wallpaper-grid 
      :wallpaper-list="wallpapers" 
      :has-more="hasMore" 
      :load-status="loadStatus"
      @wallpaper-click="navigateToDetail"
      @load-more="loadMore"
      @favorite="handleFavorite"
      @download="handleDownload"
    />
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="wallpapers.length === 0 && !loading">
      <view class="icon icon-download" style="font-size: 64px; color: #ccc;">⬇️</view>
      <text class="empty-text">暂无下载记录</text>
      <text class="empty-hint">下载喜欢的壁纸后，这里会显示记录</text>
    </view>
    
    <!-- 清除记录 -->
    <view class="clear-btn-wrapper" v-if="wallpapers.length > 0">
      <button class="clear-btn" type="default" size="mini" @click="showClearConfirm">
        清除下载记录
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import {onLoad, onShow} from "@dcloudio/uni-app"

import WallpaperGrid from '../../components/wallpaper-grid.vue';

// 页面数据状态
const wallpapers = ref([]); // 壁纸列表
const loading = ref(false); // 加载状态
const loadStatus = ref('more'); // 加载状态：more(可加载更多) | noMore(没有更多了) | error(加载失败)
const page = ref(1); // 当前页码
const size = ref(10); // 每页大小
const hasMore = ref(true); // 是否有更多数据



onLoad(() => {
  checkLoginStatus();
});

onShow(() => {
  refreshList();
});

// 检查登录状态
const checkLoginStatus = () => {
  const userToken = uni.getStorageSync('uni_id_token');
  const userInfo = uni.getStorageSync('uni-id-pages-userInfo');
  
  // 确保同时检查token和用户信息
  if (!userToken || !userInfo) {
    uni.showToast({ 
      title: '请先登录', 
      icon: 'none',
      complete: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    });
  } else {
    loadDownloadHistory();
  }
};

// 加载下载历史
const loadDownloadHistory = async () => {
  try {
    loading.value = true;
    
    // 尝试调用云函数
    try {
      // 获取用户token
      const userToken = uni.getStorageSync('uni_id_token');
      let uid = null;
      
      // 尝试获取当前用户信息，但不抛出异常
      try {
        const userInfo = uniCloud.getCurrentUserInfo();
        uid = userInfo?.uid;
      } catch (userInfoError) {
        console.log('获取用户信息失败:', userInfoError);
      }
      
      const res = await uniCloud.callFunction({
        name: 'usergetDownloads',
        data: {
          page: page.value,
          size: size.value,
          // uniIdToken: userToken,
          uid: uid
        }
      });
      
      if (res && res.result) {
        if (res.result.code === 0) {
          const dataList = res.result.data?.list || [];
          if (page.value === 1) {
            wallpapers.value = dataList;
          } else {
            wallpapers.value = [...wallpapers.value, ...dataList];
          }
          hasMore.value = res.result.data?.hasMore || false;
          
          // 如果获取到的数据为空，显示模拟数据作为兜底
          if (wallpapers.value.length === 0 && page.value === 1) {
            console.log('没有真实下载记录，');
          }
        } else if (res.result.code === 401) {
          // 用户未登录或登录过期
          uni.showToast({ 
            title: '请先登录', 
            icon: 'none',
            complete: () => {
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }
          });
        } else {
          console.log('云函数调用失败或无数据:', res.result);
          // 显示模拟数据作为兜底
          if (page.value === 1) {
          }
        }
      } else {
        console.log('云函数返回结果异常');
        // 显示模拟数据作为兜底
        if (page.value === 1) {
        }
      }
    } catch (cloudError) {
      console.log('获取下载历史失败:', cloudError);
      // 显示模拟数据作为兜底
      if (page.value === 1) {
      }
    }
    
    loadStatus.value = 'more';
  } catch (error) {
    console.error('加载下载历史失败:', error);
    loadStatus.value = 'error';
    uni.showToast({ title: '加载失败', icon: 'none' });
    // 显示模拟数据避免空白页面
    if (page.value === 1) {
    }
  } finally {
    loading.value = false;
  }
};



// 刷新列表
const refreshList = () => {
  page.value = 1;
  hasMore.value = true;
  wallpapers.value = [];
  loadDownloadHistory();
};

// 加载更多
const loadMore = async () => {
  if (!hasMore.value || loadStatus.value === 'loading') return;
  
  loadStatus.value = 'loading';
  page.value++;
  await loadDownloadHistory();
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 导航到详情
const navigateToDetail = (wallpaperId) => {
	console.log('>>>>>>>>>',wallpaperId);
  uni.navigateTo({ url: `/pages/detail/detail?id=${wallpaperId._id}` });
};

// 处理收藏
const handleFavorite = async (wallpaper) => {
  try {
    // 调用toggle云函数进行收藏操作
    const userToken = uni.getStorageSync('uni_id_token');
	const uid = uniCloud.getCurrentUserInfo().uid
    const res = await uniCloud.callFunction({
      name: 'toggle',
      data: {
        wallpaper_id: wallpaper._id,
        uniIdToken: userToken,
		uid:uid
      }
    });
    
    if (res && res.result && res.result.code === 0) {
      const index = wallpapers.value.findIndex(item => item._id === wallpaper._id);
      if (index !== -1) {
        wallpapers.value[index].is_favorite = res.result.is_favorite;
        wallpapers.value[index].favorite_count = res.result.favorite_count;
      }
      
      uni.showToast({ 
        title: res.result.is_favorite ? '收藏成功' : '取消收藏',
        icon: 'success'
      });
    } else {
      uni.showToast({ title: '操作失败', icon: 'none' });
    }
  } catch (error) {
    console.error('收藏操作失败:', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 处理下载
const handleDownload = async (wallpaper) => {
  try {
    // 请求权限
    const { authSetting } = await uni.getSetting();
    if (!authSetting['scope.writePhotosAlbum']) {
      const { confirm } = await uni.showModal({
        title: '提示',
        content: '需要您授权保存图片到相册'
      });
      
      if (!confirm) {
        return;
      }
      
      const { authSetting: newAuthSetting } = await uni.authorize({
        scope: 'scope.writePhotosAlbum'
      });
      
      if (!newAuthSetting['scope.writePhotosAlbum']) {
        uni.showToast({ title: '授权失败', icon: 'none' });
        return;
      }
    }
    
    uni.showLoading({ title: '下载中' });
    
    // 模拟下载
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // 模拟保存到相册
    // const { tempFilePath } = await uni.downloadFile({
    //   url: wallpaper.file_url
    // });
    // await uni.saveImageToPhotosAlbum({ filePath: tempFilePath });
    
    uni.hideLoading();
    uni.showToast({ 
      title: '下载成功',
      icon: 'success'
    });
    
    // 更新下载次数
    const index = wallpapers.value.findIndex(item => item._id === wallpaper._id);
    if (index !== -1) {
      wallpapers.value[index].download_count++;
    }
  } catch (error) {
    console.error('下载失败:', error);
    uni.hideLoading();
    uni.showToast({ title: '下载失败', icon: 'none' });
  }
};

// 显示清除确认
const showClearConfirm = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清除所有下载记录吗？',
    success: async (res) => {
      if (res.confirm) {
        await clearDownloadHistory();
      }
    }
  });
};

// 清除下载历史
const clearDownloadHistory = async () => {
  try {
    uni.showLoading({ title: '清除中' });
    
    // 获取用户token
    const userToken = uni.getStorageSync('uni_id_token');
    const uid =uniCloud.getCurrentUserInfo().uid
    // 调用clearHistory云函数
    const res = await uniCloud.callFunction({
      name: 'clearHistory',
      data: {
        uniIdToken: userToken,
		uid:uid
      }
    });
    
    if (res && res.result && res.result.code === 0) {
      wallpapers.value = [];
      uni.showToast({ 
        title: '清除成功',
        icon: 'success'
      });
    } else if (res && res.result && res.result.code === 401) {
      // 用户未登录或登录过期
      uni.showToast({ 
        title: '请先登录', 
        icon: 'none',
        complete: () => {
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      });
    } else {
      uni.showToast({ 
        title: res.result?.message || '清除失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('清除失败:', error);
    uni.showToast({ title: '清除失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.download-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background-color: #fff;
    border-bottom: 1px solid #f0f0f0;
    position: sticky;
    top: 0;
    z-index: 100;
    
    .header-left,
    .header-right {
      width: 40px;
    }
    
    .header-left {
      display: flex;
      align-items: center;
    }
    
    .header-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      flex: 1;
      text-align: center;
    }
  }
  
  .empty-state {
    padding: 60px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #fff;
    
    .empty-text {
      margin-top: 16px;
      font-size: 16px;
      color: #333;
    }
    
    .empty-hint {
      margin-top: 8px;
      font-size: 14px;
      color: #999;
      text-align: center;
    }
  }
  
  .clear-btn-wrapper {
    padding: 20px;
    display: flex;
    justify-content: center;
    background-color: #fff;
    margin-top: 10px;
    
    .clear-btn {
      background-color: #f5222d;
      color: #fff;
      border: none;
      padding: 8px 32px;
      border-radius: 20px;
      font-size: 14px;
      
      &:active {
        background-color: #d32424;
      }
    }
  }
}
</style>